<script setup>
import { computed, reactive, ref } from "vue";
const selected = ref(-1);
const form = reactive({
  title: "",
  date: "",
});
const currentIndex = ref(0);
const list = reactive([]);
const onSubmit = () => {
  if (selected.value === -1) {
    if (!form.title || !form.date) {
      alert("请填写完整");
      return;
    }
    list.push({ ...form, id: Date.now() + Math.floor(Math.random() * 1000) });
  } else {
    if (!form.title || !form.date) {
      alert("请填写完整");
      return;
    }
    list[selected.value] = { ...list[selected.value], ...form };
  }
  selected.value = -1;
  form.title = "";
  form.date = "";
};
const onEdit = (index) => {
  selected.value = index;
  form.title = list[index].title;
  form.date = list[index].date;
};
const onDelete = (index) => {
  list.splice(index, 1);
};
const mock = () => {
  for (let i = 0; i < 100; i++) {
    list.push({
      title: `标题${i}`,
      date: `2021-01-01`,
      id: Date.now() + Math.floor(Math.random() * 1000),
    });
  }
};
const onScroll = (e) => {
  const scrollTop = e.target.scrollTop;
  currentIndex.value = Math.floor(scrollTop / 30);
};
let  displayList =  computed(() => {
  return   list.slice(currentIndex.value, currentIndex.value + 10);
});
</script>

<template>
  <h3>{{ selected === -1 ? "添加" : "编辑" }}</h3>
  <hr />
  <form>
    <div style="display: flex; margin-bottom: 20px">
      <div>
        <label for="title">标题：</label>
        <input type="text" id="title" v-model="form.title" />
      </div>
      <div>
        <label for="date">日期：</label>
        <input type="date" id="date" v-model="form.date" />
      </div>
    </div>
  </form>
  <button @click="onSubmit" style="display: block; margin-bottom: 20px">
    提交
  </button>
  <button
    @click="
      selected = -1;
      form.title = '';
      form.date = '';
    "
    style="display: block; margin-bottom: 20px"
  >
    添加
  </button>
  <button @click="mock" style="display: block; margin-bottom: 20px">
    添加模拟数据
  </button>
  <table>
    <thead style="display:block">
      <tr style="display:flex;justify-content:space-between">
        <th>标题</th>
        <th>日期</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody
      style="height: 300px; display: block; overflow-y: auto"
      @scroll="onScroll"
    >
      <div :style="{ height: list.length * 30 + 'px' }">
        <div :style="{ height: currentIndex * 30 + 'px' }"></div>
        <tr v-for="(item, index) in displayList" :key="item.id" style="height:30px">
          <td>{{ item.title }}</td>
          <td>{{ item.date }}</td>
          <td>
            <button @click="onEdit(index)">编辑</button>
            <button @click="onDelete(index)">删除</button>
          </td>
        </tr>
      </div>
    </tbody>
  </table>
</template>
